﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace CustomControls
{
    [DefaultEvent("RowSelected")]
    public partial class DataGridControl : UserControl
    {
        #region 私有成员
        private DataGridView dataGridView;
        private CenterPanel navigationPanel;
        private Button btnAdd, btnEdit, btnDelete, btnRefresh;
        private Label lblPageInfo;
        private NumericUpDown nudPageSize;
        private Button btnFirst, btnPrev, btnNext, btnLast;
        private int currentPage = 1;
        private int pageSize = 10;
        private int totalRecords = 0;
        private DataTable dataSource;
        private bool isDirty = false;
        #endregion

        #region 构造函数
        public DataGridControl()
        {
            InitializeComponent();
            InitializeControls();
            InitializeLayout();
            InitializeEvents();
        }
        #endregion

        #region 初始化方法
        private void InitializeComponent()
        {
            this.dataGridView = new System.Windows.Forms.DataGridView();
            this.navigationPanel = new CenterPanel();
            this.btnLast = new System.Windows.Forms.Button();
            this.btnNext = new System.Windows.Forms.Button();
            this.btnPrev = new System.Windows.Forms.Button();
            this.btnFirst = new System.Windows.Forms.Button();
            this.nudPageSize = new System.Windows.Forms.NumericUpDown();
            this.lblPageInfo = new System.Windows.Forms.Label();
            this.btnRefresh = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnEdit = new System.Windows.Forms.Button();
            this.btnAdd = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
            this.navigationPanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nudPageSize)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGridView
            // 
            this.dataGridView.AllowUserToAddRows = false;
            this.dataGridView.AllowUserToDeleteRows = false;
            this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dataGridView.Location = new System.Drawing.Point(0, 0);
            this.dataGridView.Name = "dataGridView";
            this.dataGridView.ReadOnly = true;
            this.dataGridView.RowHeadersWidth = 51;
            this.dataGridView.RowTemplate.Height = 24;
            this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dataGridView.Size = new System.Drawing.Size(700, 350);
            this.dataGridView.TabIndex = 0;
            // 
            // navigationPanel
            // 
            this.navigationPanel.Controls.Add(this.btnLast);
            this.navigationPanel.Controls.Add(this.btnNext);
            this.navigationPanel.Controls.Add(this.btnPrev);
            this.navigationPanel.Controls.Add(this.btnFirst);
            this.navigationPanel.Controls.Add(this.nudPageSize);
            this.navigationPanel.Controls.Add(this.lblPageInfo);
            this.navigationPanel.Controls.Add(this.btnRefresh);
            this.navigationPanel.Controls.Add(this.btnDelete);
            this.navigationPanel.Controls.Add(this.btnEdit);
            this.navigationPanel.Controls.Add(this.btnAdd);
            this.navigationPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.navigationPanel.Location = new System.Drawing.Point(0, 350);
            this.navigationPanel.Name = "navigationPanel";
            this.navigationPanel.Size = new System.Drawing.Size(700, 50);
            this.navigationPanel.TabIndex = 1;
            // 
            // btnLast
            // 
            this.btnLast.Location = new System.Drawing.Point(350, 12);
            this.btnLast.Name = "btnLast";
            this.btnLast.Size = new System.Drawing.Size(45, 26);
            this.btnLast.TabIndex = 9;
            this.btnLast.Text = ">>";
            this.btnLast.UseVisualStyleBackColor = true;
            // 
            // btnNext
            // 
            this.btnNext.Location = new System.Drawing.Point(300, 12);
            this.btnNext.Name = "btnNext";
            this.btnNext.Size = new System.Drawing.Size(45, 26);
            this.btnNext.TabIndex = 8;
            this.btnNext.Text = ">";
            this.btnNext.UseVisualStyleBackColor = true;
            // 
            // btnPrev
            // 
            this.btnPrev.Location = new System.Drawing.Point(250, 12);
            this.btnPrev.Name = "btnPrev";
            this.btnPrev.Size = new System.Drawing.Size(45, 26);
            this.btnPrev.TabIndex = 7;
            this.btnPrev.Text = "<";
            this.btnPrev.UseVisualStyleBackColor = true;
            // 
            // btnFirst
            // 
            this.btnFirst.Location = new System.Drawing.Point(200, 12);
            this.btnFirst.Name = "btnFirst";
            this.btnFirst.Size = new System.Drawing.Size(45, 26);
            this.btnFirst.TabIndex = 6;
            this.btnFirst.Text = "<<";
            this.btnFirst.UseVisualStyleBackColor = true;
            // 
            // nudPageSize
            // 
            this.nudPageSize.Location = new System.Drawing.Point(130, 14);
            this.nudPageSize.Minimum = new decimal(new int[] {
            5,
            0,
            0,
            0});
            this.nudPageSize.Name = "nudPageSize";
            this.nudPageSize.Size = new System.Drawing.Size(60, 22);
            this.nudPageSize.TabIndex = 5;
            this.nudPageSize.Value = new decimal(new int[] {
            10,
            0,
            0,
            0});
            // 
            // lblPageInfo
            // 
            this.lblPageInfo.AutoSize = true;
            this.lblPageInfo.Location = new System.Drawing.Point(400, 18);
            this.lblPageInfo.Name = "lblPageInfo";
            this.lblPageInfo.Size = new System.Drawing.Size(92, 16);
            this.lblPageInfo.TabIndex = 4;
            this.lblPageInfo.Text = "第 1 页，共 0 页";
            // 
            // btnRefresh
            // 
            this.btnRefresh.Location = new System.Drawing.Point(570, 12);
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.Size = new System.Drawing.Size(80, 26);
            this.btnRefresh.TabIndex = 3;
            this.btnRefresh.Text = "刷新";
            this.btnRefresh.UseVisualStyleBackColor = true;
            // 
            // btnDelete
            // 
            this.btnDelete.Location = new System.Drawing.Point(480, 12);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(80, 26);
            this.btnDelete.TabIndex = 2;
            this.btnDelete.Text = "删除";
            this.btnDelete.UseVisualStyleBackColor = true;
            // 
            // btnEdit
            // 
            this.btnEdit.Location = new System.Drawing.Point(390, 12);
            this.btnEdit.Name = "btnEdit";
            this.btnEdit.Size = new System.Drawing.Size(80, 26);
            this.btnEdit.TabIndex = 1;
            this.btnEdit.Text = "编辑";
            this.btnEdit.UseVisualStyleBackColor = true;
            // 
            // btnAdd
            // 
            this.btnAdd.Location = new System.Drawing.Point(300, 12);
            this.btnAdd.Name = "btnAdd";
            this.btnAdd.Size = new System.Drawing.Size(80, 26);
            this.btnAdd.TabIndex = 0;
            this.btnAdd.Text = "添加";
            this.btnAdd.UseVisualStyleBackColor = true;
            // 
            // DataGridControl
            // 
            this.Controls.Add(this.dataGridView);
            this.Controls.Add(this.navigationPanel);
            this.Name = "DataGridControl";
            this.Size = new System.Drawing.Size(700, 400);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
            this.navigationPanel.ResumeLayout(false);
            this.navigationPanel.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nudPageSize)).EndInit();
            this.ResumeLayout(false);

        }

        private void InitializeControls()
        {
            // 配置DataGridView
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
            dataGridView.ReadOnly = true;
            dataGridView.RowTemplate.Height = 32; // 设置默认行高为32像素，可根据需要调整
            dataGridView.Dock = DockStyle.Fill;
            dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            // 配置分页控件
            nudPageSize.Minimum = 5;
            nudPageSize.Maximum = 100;
            nudPageSize.Value = 10;
            nudPageSize.Width = 60;

            // 配置按钮
            btnAdd.Text = "添加";
            btnEdit.Text = "编辑";
            btnDelete.Text = "删除";
            btnRefresh.Text = "刷新";
            btnFirst.Text = "<<";
            btnPrev.Text = "<";
            btnNext.Text = ">";
            btnLast.Text = ">>";

            // 配置页面信息标签
            lblPageInfo.Text = "第 1 页，共 0 页";
        }

        private void InitializeLayout()
        {
            //navigationPanel.Height = 120; // 原为40，改为60
            // 设置Dock样式

            dataGridView.Dock = DockStyle.Fill;
            navigationPanel.Dock = DockStyle.Bottom;
            navigationPanel.AutoSize = true; // 自动调整大小以适应内容

            // 设置导航面板的布局
            navigationPanel.Controls.Add(btnAdd);
            navigationPanel.Controls.Add(btnEdit);
            navigationPanel.Controls.Add(btnDelete);
            navigationPanel.Controls.Add(btnRefresh);
            navigationPanel.Controls.Add(lblPageInfo);
            navigationPanel.Controls.Add(nudPageSize);
            navigationPanel.Controls.Add(btnFirst);
            navigationPanel.Controls.Add(btnPrev);
            navigationPanel.Controls.Add(btnNext);
            navigationPanel.Controls.Add(btnLast);

            // 设置按钮的大小
            //btnAdd.Size = new Size(150, 60);
            //btnEdit.Size = new Size(150, 60);
            //btnDelete.Size = new Size(150, 60);
            //btnRefresh.Size = new Size(150, 60);
            //btnFirst.Size = new Size(150, 60);
            //btnPrev.Size = new Size(150, 60);
            //btnNext.Size = new Size(150, 60);
            //btnLast.Size = new Size(150, 60);
            //nudPageSize.Size = new Size(150, 60);
            //lblPageInfo.Size = new Size(150, 60);


            // 设置控件位置
            //btnAdd.Location = new Point(10, 10);
            //btnEdit.Location = new Point(100, 10);
            //btnDelete.Location = new Point(190, 10);
            //btnRefresh.Location = new Point(280, 10);
            //nudPageSize.Location = new Point(370, 10);
            //btnFirst.Location = new Point(440, 10);
            //btnPrev.Location = new Point(490, 10);
            //btnNext.Location = new Point(540, 10);
            //btnLast.Location = new Point(590, 10);
            //lblPageInfo.Location = new Point(640, 15);

            // 设置导航面板高度
            //navigationPanel.Height = 40;
        }



        private void InitializeEvents()
        {
            // 按钮事件
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            btnRefresh.Click += BtnRefresh_Click;

            // 分页按钮事件
            btnFirst.Click += BtnFirst_Click;
            btnPrev.Click += BtnPrev_Click;
            btnNext.Click += BtnNext_Click;
            btnLast.Click += BtnLast_Click;
            nudPageSize.ValueChanged += NudPageSize_ValueChanged;

            // DataGridView事件
            dataGridView.SelectionChanged += DataGridView_SelectionChanged;
        }
        #endregion

        #region 事件处理
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            OnAddRequested(EventArgs.Empty);
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                DataRowView selectedRow = dataGridView.SelectedRows[0].DataBoundItem as DataRowView;
                if (selectedRow != null)
                {
                    OnEditRequested(new DataRowEventArgs(selectedRow.Row));
                }
            }
            else
            {
                MessageBox.Show("请选择要编辑的行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                if (MessageBox.Show("确定要删除选中的记录吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DataRowView selectedRow = dataGridView.SelectedRows[0].DataBoundItem as DataRowView;
                    if (selectedRow != null)
                    {
                        OnDeleteRequested(new DataRowEventArgs(selectedRow.Row));
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择要删除的行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            OnRefreshRequested(EventArgs.Empty);
        }

        private void BtnFirst_Click(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage = 1;
                UpdateDataGridView();
            }
        }

        private void BtnPrev_Click(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage--;
                UpdateDataGridView();
            }
        }

        private void BtnNext_Click(object sender, EventArgs e)
        {
            int totalPages = GetTotalPages();
            if (currentPage < totalPages)
            {
                currentPage++;
                UpdateDataGridView();
            }
        }

        private void BtnLast_Click(object sender, EventArgs e)
        {
            int totalPages = GetTotalPages();
            if (currentPage < totalPages)
            {
                currentPage = totalPages;
                UpdateDataGridView();
            }
        }

        private void NudPageSize_ValueChanged(object sender, EventArgs e)
        {
            pageSize = (int)nudPageSize.Value;
            currentPage = 1; // 重置为第一页
            UpdateDataGridView();
        }

        private void DataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                DataRowView selectedRow = dataGridView.SelectedRows[0].DataBoundItem as DataRowView;
                if (selectedRow != null)
                {
                    OnRowSelected(new DataRowEventArgs(selectedRow.Row));
                }
            }
        }
        #endregion

        #region 私有方法
        private int GetTotalPages()
        {
            if (pageSize <= 0 || totalRecords <= 0)
                return 1;

            return (int)Math.Ceiling((double)totalRecords / pageSize);
        }

        private void UpdateDataGridView()
        {
            if (dataSource == null)
                return;

            // 计算分页数据
            DataView dv = new DataView(dataSource);
            DataTable pagedData = dv.ToTable(false, dataSource.Columns.Cast<DataColumn>().Select(c => c.ColumnName).ToArray());

            // 更新分页信息
            int totalPages = GetTotalPages();
            lblPageInfo.Text = $"第 {currentPage} 页，共 {totalPages} 页";

            // 更新按钮状态
            btnFirst.Enabled = currentPage > 1;
            btnPrev.Enabled = currentPage > 1;
            btnNext.Enabled = currentPage < totalPages;
            btnLast.Enabled = currentPage < totalPages;

            // 绑定数据
            dataGridView.DataSource = pagedData;
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 设置数据源并刷新表格
        /// </summary>
        /// <param name="data">要显示的数据</param>
        /// <param name="totalRecords">总记录数</param>
        public void SetDataSource(DataTable data, int totalRecords = -1)
        {
            this.dataSource = data;
            this.totalRecords = totalRecords > 0 ? totalRecords : (data?.Rows.Count ?? 0);
            this.currentPage = 1;

            UpdateDataGridView();
        }

        /// <summary>
        /// 刷新表格数据
        /// </summary>
        public void RefreshData()
        {
            UpdateDataGridView();
        }

        /// <summary>
        /// 获取当前选中的行
        /// </summary>
        /// <returns>选中的DataRow，如果没有选中则返回null</returns>
        public DataRow GetSelectedRow()
        {
            if (dataGridView.SelectedRows.Count > 0)
            {
                DataRowView drv = dataGridView.SelectedRows[0].DataBoundItem as DataRowView;
                return drv?.Row;
            }
            return null;
        }

        /// <summary>
        /// 设置数据行的行高
        /// </summary>
        /// <param name="height">行高（像素）</param>
        public void SetRowHeight(int height)
        {
            dataGridView.RowTemplate.Height = height;
            // 立即应用到已存在的行
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                row.Height = height;
            }
        }

        #endregion

        #region 事件定义
        /// <summary>
        /// 添加请求事件
        /// </summary>
        public event EventHandler AddRequested;

        /// <summary>
        /// 编辑请求事件
        /// </summary>
        public event EventHandler<DataRowEventArgs> EditRequested;

        /// <summary>
        /// 删除请求事件
        /// </summary>
        public event EventHandler<DataRowEventArgs> DeleteRequested;

        /// <summary>
        /// 刷新请求事件
        /// </summary>
        public event EventHandler RefreshRequested;

        /// <summary>
        /// 行选中事件
        /// </summary>
        public event EventHandler<DataRowEventArgs> RowSelected;

        /// <summary>
        /// 触发AddRequested事件
        /// </summary>
        protected virtual void OnAddRequested(EventArgs e)
        {
            AddRequested?.Invoke(this, e);
        }

        /// <summary>
        /// 触发EditRequested事件
        /// </summary>
        protected virtual void OnEditRequested(DataRowEventArgs e)
        {
            EditRequested?.Invoke(this, e);
        }

        /// <summary>
        /// 触发DeleteRequested事件
        /// </summary>
        protected virtual void OnDeleteRequested(DataRowEventArgs e)
        {
            DeleteRequested?.Invoke(this, e);
        }

        /// <summary>
        /// 触发RefreshRequested事件
        /// </summary>
        protected virtual void OnRefreshRequested(EventArgs e)
        {
            RefreshRequested?.Invoke(this, e);
        }

        /// <summary>
        /// 触发RowSelected事件
        /// </summary>
        protected virtual void OnRowSelected(DataRowEventArgs e)
        {
            RowSelected?.Invoke(this, e);
        }
        #endregion
    }

    /// <summary>
    /// 数据行事件参数
    /// </summary>
    public class DataRowEventArgs : EventArgs
    {
        public DataRow Row { get; }

        public DataRowEventArgs(DataRow row)
        {
            Row = row;
        }
    }
}